﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Launcher.UserControls
{
    public class LoadingControl : ContentControl
    {
        private int rectangle_number = 12;
        private double duration_second = 2;

        public LoadingControl()
        {
            Grid grid = new Grid();
            this.AddChild(grid);

            DoubleAnimation doubleAnimation = new DoubleAnimation
            {
                From = 1.0,
                To = 0.0,
                Duration = new Duration(TimeSpan.FromSeconds(duration_second)),
                RepeatBehavior = RepeatBehavior.Forever
            };

            for (int i = 0; i < rectangle_number; i++)
            {
                doubleAnimation.BeginTime = TimeSpan.FromSeconds(duration_second / rectangle_number * i - duration_second);

                Rectangle rectangle = new Rectangle
                {
                    Height = 10,
                    Width = 10,
                    RadiusX = 45.0,
                    RadiusY = 45.0,
                    Fill = new SolidColorBrush(Color.FromRgb(75, 0, 130))
                };

                TranslateTransform translatTransform = new TranslateTransform(30.0, 0.0);
                RotateTransform rotateTransform = new RotateTransform(360 / rectangle_number * i, 0.0, 0.0);
                TransformGroup grop = new TransformGroup();
                grop.Children.Add(translatTransform);
                grop.Children.Add(rotateTransform);
                rectangle.RenderTransform = grop;

                rectangle.BeginAnimation(Rectangle.OpacityProperty, doubleAnimation);

                grid.Children.Add(rectangle);
            }
        }

        public bool IsLoading
        {
            get
            {
                return (bool)GetValue(IsLoadingProperty);
            }
            set
            {
                SetValue(IsLoadingProperty, value);
            }
        }

        public static readonly DependencyProperty IsLoadingProperty =
            DependencyProperty.Register("IsLoading", typeof(bool), typeof(LoadingControl), new UIPropertyMetadata(true, IsLoadingChange));

        private static void IsLoadingChange(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            LoadingControl loadingControl = sender as LoadingControl;

            if ((bool)args.NewValue)
            {
                loadingControl.Visibility = Visibility.Visible;
            }
            else
            {
                loadingControl.Visibility = Visibility.Collapsed;
            }
        }
    }
}
